<template>
	<div class="archives_permitinfo_info">
		<div class="formPart">
			<v-form
				v-for="(item, i) in formListData"
				:key="i"
				:formList="item.list"
				:title="item.title"
				:outofSubmit="true"
				ref="formData"
			></v-form>
			<div style="text-align:center" v-if="isEdit">
				<el-button type="primary" style="width: 130px" @click="submit"
					>保存</el-button
				>
				<el-button type="info" style="width: 130px;" @click="cancel"
					>取消</el-button
				>
			</div>
		</div>
	</div>
</template>

<script>
import VForm from "@/components/luyiming/VueEleForm/index.vue";
import {
	getRadTypePro,
	getRadTypeMarket,
	getRadTypeUse,
	getEnterpriseType,
	getEnterpriseStatus,
	getApproveOrg,
	getLicensingOrg
} from "@/api/RCIM/RCIM-select";
import control from "../mixins/control";
import { cloneDeep } from "lodash";
import moment from "moment";
import {
	insertEnterpriseRadPermit,
	getEnterpriseRadPermit
} from "@/api/RCIM/RCIM-archives";
export default {
	name: "archives_permitinfo_info",
	components: {
		VForm
	},
	mixins: [control],
	data() {
		return {
			tableVal: {},
			isEdit: false,
			tableLayout: [
				{
					title: "注册地址",
					child: [
						{
							label: "注册地行政区域规划",
							key: "se",
							width: "50%"
						},
						{
							label: "注册地行政区域规划",
							key: "se",
							width: "50%"
						},
						{
							label: "注册地行政区域规划",
							key: "se",
							width: "50%"
						},
						{
							label: "注册地行政区域规划",
							key: "se",
							width: "50%"
						}
					]
				}
			],
			formList: [
				{
					list: [
						{
							type: "input",
							label: "部门名称",
							width: "23%",
							maxlength: "20",
							showWordLimit: true,
							placeholder: "请输入",
							moduleKey: "entName_0",
							validate: function() {
								return [
									{
										required: false,
										message: "请输入部门名称",
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "input",
							label: "地址",
							width: "23%",
							maxlength: "50",
							showWordLimit: true,
							placeholder: "请输入",
							moduleKey: "address_0",
							validate: function() {
								return [
									{
										required: false,
										message: "请输入地址",
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "input",
							label: "负责人",
							width: "23%",
							maxlength: "10",
							showWordLimit: true,
							placeholder: "请输入",
							moduleKey: "leader_0",
							validate: function() {
								return [
									{
										required: false,
										message: "请输入负责人",
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "input",
							label: "工作场合",
							labelWidth: "100px",
							width: "30.8%",
							maxlength: "20",
							showWordLimit: true,
							placeholder: "请输入",
							moduleKey: "workplace_0",
							after: {
								width: "30%",
								content: this.renderBtn3
							},
							validate: function() {
								return [
									{
										required: false,
										message: "请输入工作场合",
										trigger: "blur"
									}
								];
							}
						}
					],
					title: "涉源部门"
				},
				{
					list: [
						{
							type: "checkbox-group",
							label: "生产",
							width: "100%",
							optionsType: {
								id: "label",
								label: "value"
							},
							labelWidth: "140px",
							moduleKey: "producation",
							placeholder: "请选择",
							children: "checkbox",
							defaultValue: [],
							fetch: getRadTypePro,
							options: []
						},
						{
							type: "checkbox-group",
							label: "销售",
							optionsType: {
								id: "label",
								label: "value"
							},
							labelWidth: "140px",
							width: "100%",
							moduleKey: "market",
							placeholder: "请选择",
							children: "checkbox",
							fetch: getRadTypeMarket,
							defaultValue: [],
							options: []
						},
						{
							type: "checkbox-group",
							label: "使用",
							optionsType: {
								id: "label",
								label: "value"
							},
							labelWidth: "140px",
							width: "100%",
							moduleKey: "use",
							placeholder: "请选择",
							children: "checkbox",
							fetch: getRadTypeUse,
							defaultValue: [],
							options: []
						}
					],
					title: "放源种类和范围"
				},
				{
					list: [
						{
							type: "select",
							label: "单位类型",
							labelWidth: "100px",
							width: "25%",
							placeholder: "请输入",
							moduleKey: "unitType",
							children: "option",
							fetch: getEnterpriseType,
							options: [],
							validate: function() {
								return [
									{
										required: false,
										message: "请选择单位类型",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "select",
							label: "单位状态",
							labelWidth: "100px",
							width: "25%",
							placeholder: "请输入",
							moduleKey: "unitStatus",
							children: "option",
							fetch: getEnterpriseStatus,
							options: [
								{
									label: "参数",
									id: "demo"
								}
							],
							validate: function() {
								return [
									{
										required: false,
										message: "请选择单位状态",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "select",
							label: "发证机关",
							labelWidth: "100px",
							width: "25%",
							placeholder: "请输入",
							moduleKey: "stdcallDep",
							children: "option",
							fetch: getLicensingOrg,
							options: [
								{
									label: "参数",
									id: "demo"
								}
							],
							validate: function() {
								return [
									{
										required: false,
										message: "请选择发证机关",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "input",
							label: "证书编号",
							labelWidth: "100px",
							width: "24.9%",
							placeholder: "请输入",
							maxlength: "20",
							showWordLimit: true,
							moduleKey: "credentialNo",
							validate: function() {
								return [
									{
										required: false,
										message: "请输入证书编号",
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "date-picker",
							label: "发证日期",
							labelWidth: "100px",
							defaultValue: new Date(),
							typeProp: "date",
							width: "25%",
							placeholder: "请输入",
							moduleKey: "issueDate",
							validate: function() {
								return [
									{
										required: false,
										message: "请选择发证日期",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "date-picker",
							label: "有效日期",
							labelWidth: "100px",
							defaultValue: new Date(),
							typeProp: "date",
							width: "25%",
							placeholder: "请输入",
							moduleKey: "validDate",
							validate: function() {
								return [
									{
										required: false,
										message: "请选择有效日期",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "select",
							label: "审批机关",
							labelWidth: "100px",
							width: "25%",
							placeholder: "请输入",
							moduleKey: "approvalDep",
							children: "option",
							fetch: getApproveOrg,
							options: [
								{
									label: "参数",
									id: "demo"
								}
							],
							validate: function() {
								return [
									{
										required: false,
										message: "请选择审批机关",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "input",
							label: "许可证件",
							labelWidth: "100px",
							width: "25%",
							maxlength: "20",
							showWordLimit: true,
							placeholder: "请输入",
							moduleKey: "permitCard",
							validate: function() {
								return [
									{
										required: false,
										message: "请输入许可证件",
										trigger: "blur"
									}
								];
							}
						}
					],
					title: "许可证信息"
				}
			],
			formListData: [],
			formIndex: 0
		};
	},
	created() {
		this.cancel();
	},
	methods: {
		/**
		 * @desc 删除数据
		 * @param {Object} row 表格行数据
		 */
		delet(row) {
			this.$confirm("确认要删除吗？")
				.then(_ => {
					deleteRad(row.id).then(res => {
						if (res.code === 200) {
							this.getList();
							return this.$message({
								type: "success",
								message: "删除成功"
							});
						}
						return this.$message({
							type: "error",
							message: "删除失败"
						});
					});
				})
				.catch(_ => {});
		},
		/**
		 * @desc 获取数据
		 */
		getList() {
			return getEnterpriseRadPermit({ id: this.entData.id }).then(res => {
				let values = [{}, {}, {}];
				let data = res.data;
				this.formList[0].list.length = 4;
				this.formIndex = 0;
				if (data.conditionList) {
					for (
						let index = 0;
						index < data.conditionList.length;
						index++
					) {
						let v = data.conditionList[index];
						if (index > 0) {
							this.append();
						}
						for (let key in v) {
							let newKey = key;
							if (newKey === "departmentName") {
								newKey = "entName";
							}
							data[newKey + "_" + index] = v[key];
							values[0][newKey + "_" + index] = v[key];
						}
					}
				}
				const first = ["producation", "use", "market"];
				const second = [
					"permitCard",
					"approvalDep",
					"validDate",
					"issueDate",
					"credentialNo",
					"stdcallDep",
					"unitStatus",
					"unitType"
				];
				first.forEach(v => {
					values[1][v] = data?.[v]?.split(",") || [];
				});
				second.forEach(v => {
					values[2][v] = data?.[v] || "";
				});
				this.$nextTick(() => {
					const parent = this.$refs.formData.forEach((item, ide) => {
						item.setDefaultValue(values[ide]);
						// ()
						setTimeout(item.clearValedate ? item.clearValedate : () => {}, 100)
					});
				});
			});
		},
		/**
		 * @desc 编辑查看表格数据
		 */
		handleEdit() {
			this.isEdit = true;
			const newForm = cloneDeep(this.formListData);
			newForm.forEach(item => {
				item.list.forEach(itemForm => {
					if (itemForm.moduleKey) {
						itemForm.disabled = false;
					}
				});
			});
			this.formListData = newForm;
		},
		/**
		 * @desc 关闭弹窗
		 */
		cancel() {
			this.isEdit = false;
			const newForm = cloneDeep(this.formList);
			this.formListData = newForm;
			this.getList().then(res => {
				const newForm1 = cloneDeep(this.formListData);
				newForm1.forEach(item => {
					item.list.forEach(itemForm => {
						if (itemForm.moduleKey) {
							itemForm.disabled = true;
						}
					});
				});
				this.formListData = newForm1;
			});
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn(h) {
			return <div class="btn_wrap"></div>;
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn1(h, content) {
			return (
				<div class="btn_wrap">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-plus"
						on-click={() => this.append()}
					>
						添加
					</el-button>
					<el-button
						size="mini"
						type="text"
						style="color:red"
						icon="el-icon-delete"
						on-click={() => this.remove(content)}
					>
						删除
					</el-button>
				</div>
			);
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn2(h, content) {
			return (
				<div class="btn_wrap">
					<el-button
						size="mini"
						type="text"
						style="color:red"
						icon="el-icon-delete"
						on-click={() => this.remove(content)}
					>
						删除
					</el-button>
				</div>
			);
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn3(h) {
			return (
				<div class="btn_wrap">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-plus"
						on-click={() => this.append()}
					>
						添加
					</el-button>
				</div>
			);
		},
		/**
		 * @desc 处理表单数据
		 * @param {Object} formData 表单数据
		 */
		handleForm() {
			let formData = {},
				conditionList = [];
			// 循环多个表单，组成一个值
			for (const v of this.$refs.formData) {
				formData = { ...v.form, ...formData };
			}

			// 循环表单寻找相同数据的
			for (const key in formData) {
				if (key.indexOf("_") != -1) {
					// 切割字符串，第一个为需要的key
					const anKey = key.split("_")[0];
					let obj = {};
					obj[anKey] = formData[key];
					// 归类用的字段
					obj["index"] = key.split("_")[1];
					conditionList.push(obj);
					// 删除不需要的属性
					delete formData[key];
				}
			}
			var nameContainer = []; // 针对键index进行归类的容器
			conditionList.forEach(item => {
				item.index = Number(item.index);
				nameContainer[item.index] = nameContainer[item.index] || {};

				//当逻辑或||时，找到为true的分项就停止处理，并返回该分项的值，否则执行完，并返回最后分项的值。
				nameContainer[item.index][Object.keys(item)[0]] =
					item[Object.keys(item)[0]];
			});
			formData["conditionList"] = nameContainer.filter(item => item);
			formData.id = this.entData.id;
			formData.issueDate = moment(formData.issueDate).format(
				"YYYY-MM-DD"
			);
			formData.validDate = moment(formData.validDate).format(
				"YYYY-MM-DD"
			);
			formData.market =
				(formData.market instanceof Array &&
					formData.market.join(",")) ||
				"";
			formData.use =
				(formData.use instanceof Array && formData.use.join(",")) || "";
			formData.producation =
				(formData.producation instanceof Array &&
					formData.producation.join(",")) ||
				"";
			formData.conditionList = JSON.stringify(formData.conditionList);

			return formData;
		},
		/**
		 * @desc 新增、编辑数据
		 * @param {Object} formData 表单数据
		 */
		submit() {
			let isGo = true;
			this.$refs.formData.forEach((item, ide) => {
				item.validate((type) => {
					if(!type) isGo = false;
				})
			});
			if(!isGo){
				return
			}
			let formData = this.handleForm();
			console.log(formData);
			insertEnterpriseRadPermit(formData).then(res => {
				if (res.code === 200) {
					this.dialogFormVisible = false;
					this.cancel();
					return this.$message({
						type: "success",
						message: "添加成功"
					});
				}
				return this.$message({
					type: "success",
					message: "添加失败"
				});
			});
		},
		/**
		 * @desc 新增表单行
		 */
		appendContent() {
			this.formIndex++;
			return [
				{
					type: "input",
					label: "部门名称",
					width: "23%",
					maxlength: "20",
					showWordLimit: true,
					placeholder: "请输入",
					moduleKey: "entName_" + this.formIndex
				},
				{
					type: "input",
					label: "地址",
					width: "23%",
					maxlength: "50",
					showWordLimit: true,
					placeholder: "请输入",
					moduleKey: "address_" + this.formIndex
				},
				{
					type: "input",
					label: "负责人",
					width: "23%",
					maxlength: "10",
					showWordLimit: true,
					placeholder: "请输入",
					moduleKey: "leader_" + this.formIndex
				},
				{
					type: "input",
					label: "工作场合",
					labelWidth: "100px",
					width: "31%",
					maxlength: "20",
					showWordLimit: true,
					placeholder: "请输入",
					moduleKey: "workplace_" + this.formIndex,
					after: {
						width: "30%",
						content: this.renderBtn1
					}
				}
			];
		},
		/**
		 * @desc 新增表单行
		 */
		append() {
			const listIndex = 0;
			const last = this.formListData[listIndex].list.length - 1;
			if (last === 3) {
				this.formListData[listIndex].list[
					last
				].after.content = this.renderBtn;
			} else {
				this.formListData[listIndex].list[
					last
				].after.content = this.renderBtn2;
			}

			this.formListData[listIndex].list.push(...this.appendContent());
		},
		/**
		 * @desc 删除表单行
		 */
		remove(c) {
			const listIndex = 0;
			let list = [];
			let delKeys = [];
			list = this.formListData[listIndex].list.filter(v => {
				if (v.moduleKey.split("_")[1] === c.moduleKey.split("_")[1]) {
					delKeys.push(v.moduleKey);
				}
				return v.moduleKey.split("_")[1] != c.moduleKey.split("_")[1];
			});
			this.$refs.formData[0].deleteKeys(delKeys);
			const last = list.length - 1;
			if (last === 3) {
				list[last].after.content = this.renderBtn3;
			} else {
				list[last].after.content = this.renderBtn1;
			}
			this.formListData[listIndex].list = list;
		}
	}
};
</script>

<style lang="scss" scoped>
.archives_permitinfo_info {
	/deep/ {
		.el-input.is-disabled .el-input__inner {
			color: #333;
		}
		.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
			border-color: #333;
		}
	}
	.v-table {
		border-top: 1px solid #ccc;
		border-left: 1px solid #ccc;
		width: 100%;
		.v-table-block {
			font-size: 0;
			.v-table-title {
				font-size: 16px;
				border-bottom: 1px solid #ccc;
				border-right: 1px solid #ccc;
				display: inline-block;
				vertical-align: top;
				background-color: #d5e9fa;
				text-align: center;
				width: 130px;
				font-weight: 100;
			}
		}
		.v-table-item {
			font-size: 16px;
			border-bottom: 1px solid #ccc;
			border-right: 1px solid #ccc;
			display: inline-block;
			vertical-align: top;
			height: 40px;
			line-height: 40px;
			.v-table-label {
				width: 180px;
				height: 100%;
				font-weight: 100;
				text-align: center;
				display: inline-block;
				vertical-align: top;
				background-color: #d5e9fa;
				border-right: 1px solid #ccc;
			}
			.v-table-value {
				display: inline-block;
				vertical-align: top;
				width: calc(100% - 136px);
				height: 100%;
				text-align: center;
			}
		}
	}
}
</style>
